package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.CheckDetailed;
import com.ruoyi.system.domain.MedicalRecord;
import com.ruoyi.system.mapper.CheckDetailedMapper;
import com.ruoyi.system.service.ICheckDetailedService;
import com.ruoyi.system.service.impl.ItemServiceImpl;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.web.controller.tool.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 检查详情Controller
 *
 * @author ruoyi
 * @date 2023-07-04
 */
@Api(tags = "检查详情模块")
@RestController
@RequestMapping("/system/CheckDetailed")
public class CheckDetailedController extends BaseController {
    @Autowired
    ItemServiceImpl itemService;
    @Autowired
    SysUserServiceImpl sysUserService;
    @Autowired
    SysDeptServiceImpl sysDeptService;
    @Autowired
    private ICheckDetailedService checkDetailedService;
    @Autowired(required = false)
    CheckDetailedMapper checkDetailedMapper;


    private Wrap convert(CheckDetailed origin) {
        Wrap tempWrap = new Wrap();
        tempWrap.CheckProjId = itemService.getById(origin.getId()).getItemName();
        if (itemService.getById(origin.getId()) != null) {
            tempWrap.CheckProjId = itemService.getById(origin.getId()).getItemName();
        }
        if (sysUserService.selectUserById(Long.parseLong(origin.getFromUserId())) != null) {
            tempWrap.FromUserId = sysUserService.selectUserById(Long.parseLong(origin.getFromUserId())).getUserName();
        }
        if (sysDeptService.selectDeptById(origin.getDeptId()) != null) {
            tempWrap.DeptId = sysDeptService.selectDeptById(origin.getDeptId()).getDeptName();
        }
        if (sysUserService.selectUserById(origin.getCheckUserId()) != null) {
            tempWrap.CheckUserId = sysUserService.selectUserById(origin.getCheckUserId()).getUserName();
        }
        if (sysUserService.selectUserById(origin.getEnterUserId()) != null) {
            tempWrap.EnterUserId = sysUserService.selectUserById(origin.getEnterUserId()).getUserName();
        }
        tempWrap.CheckDetailed = origin;
        return tempWrap;
    }

    /**
     * 新增检查详情
     */
    @ApiOperation(value = "新增检查详情")
    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:add')")
    @Log(title = "检查详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheckDetailed checkDetailed) {
        return toAjax(checkDetailedService.save(checkDetailed));
    }

    /**
     * 根据病历Id获取检查详情
     */
    @ApiOperation(value = "查询检查详情列表")
    @GetMapping("/getByMedicalRecordId")
    public List<CheckDetailed> getByMedicalRecordId(@RequestParam("MedicalId") Long MedicalId) {
        QueryWrapper<CheckDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalId", MedicalId);
        return checkDetailedService.list(queryWrapper);
    }

    /**
     * 查询检查详情列表
     */
    @ApiOperation(value = "查询检查详情列表")
    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:list')")
    @GetMapping("/list")
    public Page<Wrap> list(CheckDetailed entity, Page<CheckDetailed> page) {
        Page<Wrap> pageWrap = new Page<>();
        LambdaQueryWrapper<CheckDetailed> lambdaQueryWrapper = new LambdaQueryWrapper<CheckDetailed>();
        Page<CheckDetailed> pageCheckDetailed = checkDetailedService.page(page, lambdaQueryWrapper);
        List<Wrap> wraps = new ArrayList<>();
        List<CheckDetailed> checkDetaileds = pageCheckDetailed.getRecords();
        for (CheckDetailed item : checkDetaileds) {
            if (item.getCheckState() >= 2) {
                wraps.add(convert(item));
            }

        }
        pageWrap.setRecords(wraps);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPage(pageWrap, pageCheckDetailed);
        return pageWrap;
    }

    /**
     * 导出检查详情列表
     */
    @ApiOperation(value = "导出检查详情列表")
    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:export')")
    @Log(title = "检查详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheckDetailed checkDetailed) {
        LambdaQueryWrapper<CheckDetailed> queryWrapper = new LambdaQueryWrapper<>();
        List<CheckDetailed> list = checkDetailedService.list(queryWrapper);
        ExcelUtil<CheckDetailed> util = new ExcelUtil<CheckDetailed>(CheckDetailed.class);
        util.exportExcel(response, list, "检查详情数据");
    }

    /**
     * 获取检查详情详细信息
     */
//    @ApiOperation(value = "获取检查详情详细信息")
//    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:query')")
//    @GetMapping(value = "/{Id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return success(checkDetailedService.getById(id));
//    }


    /**
     * 修改检查详情
     */
    @ApiOperation(value = "修改检查详情")
    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:edit')")
    @Log(title = "检查详情", businessType = BusinessType.UPDATE)
    @PutMapping("/request")
    public AjaxResult edit(@RequestBody CheckDetailed checkDetailed) {
        return toAjax(checkDetailedService.updateById(checkDetailed));
    }

    /**
     * 删除检查详情
     */
//    @ApiOperation(value = "删除检查详情")
//    @PreAuthorize("@ss.hasPermi('system:CheckDetailed:remove')")
//    @Log(title = "检查详情", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{Ids}")
//    public AjaxResult remove(@PathVariable Long[] Ids) {
//        return toAjax(checkDetailedService.removeBatchByIds(Arrays.asList(Ids)));
//    }

    /**
     * 获取科室名称
     */
    @GetMapping("/getDeptName")
    public String getDeptName(@RequestParam("DeptId") Long Id) {
        return sysDeptService.selectDeptById(Id).getDeptName();
    }

    /**
     * 获取检查项目列表
     */
    @GetMapping("/getCheckDetailedByDeptId/{DeptId}")
    public List<Wrap> getCheckDetailedByDeptId(@PathVariable Long DeptId) {
        System.out.println(DeptId);
        QueryWrapper<CheckDetailed> QueryWrapper = new QueryWrapper();
        QueryWrapper.orderBy(false, true, "CheckState");
        if (DeptId != 0) {
            QueryWrapper.eq("DeptId", DeptId);
        }
        QueryWrapper.ge("CheckState", 2);
        List<CheckDetailed> checkDetaileds = checkDetailedMapper.selectList(QueryWrapper);
        List<Wrap> wraps = new ArrayList<>();
        for (CheckDetailed item : checkDetaileds
        ) {
            wraps.add(convert(item));
        }
        return wraps;
    }


    /**
     * 更新状态
     */
    @GetMapping("/setCheckState")
    public AjaxResult setCheckState(@RequestParam("Id") Long Id, @RequestParam("userId") Long userId) {
        CheckDetailed checkDetailed = new CheckDetailed();
        checkDetailed.setCheckState(3L);
        checkDetailed.setId(Id);
        checkDetailed.setCheckUserId(userId);
        checkDetailed.setInspectTime(new Date(System.currentTimeMillis()));
        return toAjax(checkDetailedService.updateById(checkDetailed));
    }

    /**
     * 结果录入
     */
    @PostMapping("/enter")
    public AjaxResult enter(@RequestBody CheckDetailed checkDetailed) {
        checkDetailed.setCheckState(4L);
        return toAjax(checkDetailedService.updateById(checkDetailed));
    }

    /**
     * 通过项目状态搜索
     */
    @GetMapping("/CheckState")
    public List<Wrap> getByCheckState(@RequestParam("CheckState") Long CheckState) {
        QueryWrapper<CheckDetailed> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("CheckState", CheckState);
        List<CheckDetailed> checkDetaileds = checkDetailedMapper.selectList(QueryWrapper);
        List<Wrap> wraps = new ArrayList<>();
        for (CheckDetailed item : checkDetaileds
        ) {
            wraps.add(convert(item));
        }
        return wraps;
    }

    /**
     * 通过病历id搜索
     */
    @GetMapping("/MedicalId")
    public Wrap getByMedicalId(@RequestParam("MedicalId") Long MedicalId) {
        QueryWrapper<CheckDetailed> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("MedicalId", MedicalId);
        return convert(checkDetailedService.getOne(QueryWrapper));
    }


    private class Wrap implements Serializable {
        CheckDetailed CheckDetailed;
        String CheckProjId = "";
        String FromUserId = "";
        String DeptId = "";

        String EnterUserId = "";
        String CheckUserId = "";

        @JsonProperty("EnterUserId")
        public String getEnterUserId() {
            return EnterUserId;
        }

        @JsonProperty("CheckUserId")
        public String getCheckUserId() {
            return CheckUserId;
        }

        @JsonProperty("DeptId")
        public String getDeptId() {
            return DeptId;
        }

        public void setDeptId(String DeptId) {
            DeptId = DeptId;
        }

        @JsonProperty("CheckDetailed")
        public com.ruoyi.system.domain.CheckDetailed getCheckDetailed() {
            return CheckDetailed;
        }

        public void setCheckDetailed(com.ruoyi.system.domain.CheckDetailed checkDetailed) {
            CheckDetailed = checkDetailed;
        }

        @JsonProperty("CheckProjId")
        public String getCheckProjId() {
            return CheckProjId;
        }
        public void setCheckProjId(String CheckProjId) {
            CheckProjId = CheckProjId;
        }

        @JsonProperty("FromUserId")
        public String getFromUserId() {
            return FromUserId;
        }

        public void setFromUserId(String FromUserId) {
            FromUserId = FromUserId;
        }
    }
}
